<template lang="pug">
  .page
    .search-form.mb-10.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户名称：
          Input(v-model="name" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户所属：
          .choose-saler
            Tooltip(placement="bottom" max-width="200" :disabled="!tipIsShow" theme="light")
              Input.input(v-model="dolderNames" type="text" readonly clearable @on-clear="salersClear")
              div(slot="content")
                .font-14 {{dolderNames}}
            .button(@click="chooseSaler") 选择
          //- Input(v-model="salerName" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 企业性质：
          Select(v-model="character"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in characterArr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 企业规模：
          Select(v-model="size"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in sizeArr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 所属行业：
          Select(v-model="businessType"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in customerBusinesstype_arr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 注册资本：
          Input.unit-input(v-model="registerCapital")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户类型：
          Select(v-model="signedType"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in customersignedtype" :value="item.key" :key="index") {{ item.value }}
          Button.ml-15(type="info" @click="searchBtn") 查询
    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="setThead" :data="listData" @on-selection-change="tableSelectChange")
        div(slot="header")
          .pull-left.table-title-lefttxt
            span.leftText
              | 我的潜在客户数:
              span.text-info.pl-5.pr-5.font-weight {{codeTotal}}
          .pull-right.table-title-btns
            Button(v-if="hasHRDC_ExportPotentialCustomers" type="info" @click="exportBtn") 客户导出
        template(slot-scope="{ row, index }" slot="name")
          .u-d-info(@click="gotoDetail(row.customerId)") {{row.customerName}}
        template(slot-scope="{ row, index }" slot="communicate")
          Button.mr-5(type="info" size="small" @click="addCommunication(row.customerId)") 添加
          Button.mr-5(type="info" size="small" @click="checkCommunication(row.customerId)") 查看
        template(slot-scope="{ row, index }" slot="action")
          Button.mr-5(v-if="hasHRDC_PostRequirement" type="text" size="small" @click="createBtn(row)") 添加需求
          Button.mr-5(v-if="hasHRDC_SetPublic" type="text" size="small" @click="setPublic(row.customerId)") 抛出
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
      //- div(style="margin: 10px;overflow: hidden")
      //-   div(style="float: right;")
      //-     Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    Modal(v-model="createModal" title="添加需求")
      Form(ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="130")
        FormItem(label="客户需求：" prop="requirementType")
          Cascader.input-has-border(:data="requirementArr" @on-change="requirementTypeChange")
          //- Select.input-has-border(v-model="formValidate.requirementType" label-in-value placeholder="请选择" clearable @on-change="requirementTypeChange")
          //-   Option(v-for="(item, index) in requirementArr" :value="item.value" :key="index") {{ item.text }}
        FormItem(label="需求描述：")
          Input.input-has-border(v-model="formValidate.brief" type="text" placeholder="描述...")
        FormItem(label="预计启动时间：" prop="planStartTime")
          DatePicker.input-has-border(:value="formValidate.planStartTime" type="date" placeholder="请选择" style="display:block" @on-change="planStartTimeChange")
        FormItem(label="预算金额：" prop="budget")
          Input.input-has-border(v-model="formValidate.budget" placeholder="请输入")
        FormItem(label="完成时间：" prop="completeTime")
          DatePicker.input-has-border(:value="formValidate.completeTime" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请选择" style="display:block" @on-change="completeTimeChange")
      template(slot="footer")
        Button(type="info" :loading="btnLoading" :disabled="btnLoading" @click="handleSubmit('formValidate')") 保存并填写2D诊断表
        Button(@click="closeModal") 取消
    createCommunication(ref="createCommunication" :customerId="customerId" :contact_arr="contact_arr" :communicationtype="communicationtype")
    checkCommunication(ref="checkCommunication" :customerId="customerId" :communicationList="communicationList" :communicationTotal="communicationTotal" @get-list="getCommunicationList")
    diagnose(ref="diagnose" :requirementId="requirementId" :customerName="customerName" @close-modal="closeModal")
    visibvleTreeList(ref="treeModal" :treeData="treeData" @on-change="getSalerId")
</template>

<script>
import HRDCCustomerApi from '@/api/HRDCCustomer.api.js'
import Mixin from '../coustomerMixin.js'
import diagnose from './modal/2D.vue'
import createCommunication from '../../HRDC-common/communication/create.vue'
import checkCommunication from '../../HRDC-common/communication/check.vue'
import { Common } from '@/utils/common.js'
export default {
  name: 'h-c-potential',
  data () {
    return {
      customerName: '',
      createModal: false,
      name: '',
      salerName: '',
      budgetId: '', // 需求ID
      character: '', // 企业性质
      size: '', // 企业规模
      businessType: '', // 所属行业
      registerCapital: '', // 注册资本
      signedType: '', // 客户类型
      thead: ['selection', 'createTime', 'signedTypeName', 'name', 'budgetDetail', 'plan', 'historySuppliers', 'historyProjects', 'characterName', 'businessTypeName', 'registerCapital', 'size',  'holders', 'communicate', 'createrName', 'action'],
      listData: [],
      loading: false,
      btnLoading: false,
      codeTotal: 0,
      PageIndex: 1,
      PageSize: 10,
      requirementId: '', // 新建需求的id
      // hasSave: true, // 是否已经保存需求
      requirementArr: [],
      formValidate: {
        brief: '',
        requirementType: '',
        requirementTypeName: '',
        planStartTime: '',
        budget: '',
        completeTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
      },
      ruleValidate: {
        requirementType: [
          { required: true, message: '需求不能为空', trigger: 'change' }
        ],
        budget: [
          { required: true, message: '预算不能为空', trigger: 'blur' }
        ],
        planStartTime: [
          { required: true, message: '启动时间不能为空', trigger: 'change' }
        ],
        completeTime: [
          { required: true, message: '完成时间不能为空', trigger: 'change' }
        ]
      },
      // arrListDown: {
      //   customersignedtype: []
      // },
      customersignedtype: []
    }
  },
  mixins: [Mixin],
  components: {
    createCommunication,
    checkCommunication,
    diagnose
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasHRDC_GetPotentialCustomers () {
      return this.actionArr.indexOf('HRDC_GetPotentialCustomers') > -1
    },
    // 抛出
    hasHRDC_SetPublic () {
      return this.actionArr.indexOf('HRDC_SetPublic') > -1
    },
    // 添加需求
    hasHRDC_PostRequirement () {
      return this.actionArr.indexOf('HRDC_PostRequirement') > -1
    },
    // 导出
    hasHRDC_ExportPotentialCustomers () {
      return this.actionArr.indexOf('HRDC_ExportPotentialCustomers') > -1
    },
    setThead () {
      return this.getTableColumns(this.thead)
    }
  },
  created () {
    this.getEnum()
    this.getList()
    // this.getRequirementArr()
    this.getSelectIdTreeSource()
  },
  watch: {
    $route (to, from) {
      if (to.name === 'h-c-potential') {
        this.getList()
      }
    }
  },
  methods: {
    // 获取客户列表
    getList () {
      this.loading = true
      HRDCCustomerApi.GetPotentialCustomers({
        name: this.name,
        salerName: this.salerName,
        HolderIds: this.salesIds,
        Character: this.character,
        Size: this.size,
        BusinessType: this.businessType,
        RegisterCapital: this.registerCapital,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize,
        SignedType: this.signedType
      }).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.codeTotal = res.data.totalRows
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    closeModal () {
      this.createModal = false
      this.formValidate = {
        brief: '',
        requirementType: '',
        requirementTypeName: '',
        planStartTime: '',
        budget: ''
      }
      this.$refs['formValidate'].resetFields()
    },
    // getRequirementArr () {
    //   HRDCCustomerApi.GetSelectIdList().then(res => {
    //     if (res.data.success) {
    //       this.requirementArr = res.data.data
    //     } else {
    //       this.$Message.error(res.data.message)
    //     }
    //   })
    // },
    getSelectIdTreeSource () {
      HRDCCustomerApi.GetSelectIdTreeSource().then(res => {
        if (res.data.success) {
          this.requirementArr = res.data.data
        } else {
          this.$Message.error(res.data.message)
        }
      })
    },
    requirementTypeChange (value, selectedData) {
      if (value.length > 0) {
        this.formValidate.requirementType = value[value.length - 1]
        this.formValidate.requirementTypeName = selectedData[selectedData.length - 1].label
      } else {
        this.formValidate.requirementType = ''
        this.formValidate.requirementTypeName = ''
      }
      // if (val) {
      //   // this.requirementType = val.value
      //   this.formValidate.requirementTypeName = val.label
      // } else {
      //   // this.requirementType = ''
      //   this.formValidate.requirementTypeName = ''
      // }
    },
    // 添加需求
    createBtn (row) {
      this.customerName = row.customerName
      this.customerId = row.customerId
      this.budgetId = row.id
      this.formValidate.completeTime = this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
      this.createModal = true
      this.formValidate = {
        brief: '',
        requirementType: '',
        requirementTypeName: '',
        planStartTime: '',
        budget: '',
        completeTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
      }
      this.$refs['formValidate'].resetFields()
    },
    // 提交需求并填写2D诊断表
    handleSubmit (name) {
      // this.$refs.diagnose.modalOpen()
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.diagnose()
        } else {
          this.$Message.warning('有必填项未填!')
        }
      })
    },
    // 查询
    searchBtn () {
      this.PageIndex = 1
      this.getList()
    },
    // 保存需求并打开2D诊断表
    diagnose () {
      this.btnLoading = true
      HRDCCustomerApi.PostRequirement(Object.assign({ CustomerId: this.customerId, budgetId: this.budgetId }, this.formValidate)).then(res => {
        this.btnLoading = false
        if (res.data.success) {
          this.requirementId = res.data.data.id
          this.$refs.diagnose.modalOpen()
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 抛出
    setPublic (id) {
      HRDCCustomerApi.SetPublic({
        id: id
      }).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.getList()
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    planStartTimeChange (val) {
      console.log(val)
      this.formValidate.planStartTime = val
      console.log(this.formValidate.planStartTime)
    },
    completeTimeChange (val) {
      this.formValidate.completeTime = val
    },
    // 客户导入
    importBtn () {

    },
    // 客户导出
    exportBtn () {
      HRDCCustomerApi.exportPotentialCustomers({
        selectedIds: this.ids,
        name: this.name,
        salerName: this.salerName,
        HolderIds: this.salesIds,
        Character: this.character,
        Size: this.size,
        BusinessType: this.businessType,
        RegisterCapital: this.registerCapital,
        SignedType: this.signedType
      }).then(res => {
        if (res.data.success) {
          let objectUrl = res.data.data
          console.log(objectUrl)
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    tableSelectChange () {

    },
    pageChangeFn (val) {
      this.PageIndex = val
      this.getList()
    },
    onpageSizeChange (val) {
      this.PageSize = val
      this.getList()
    }
  }
}
</script>

<style>

</style>
